﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Web;

namespace OgilvyOne.UKNow.Utility
{
    public class AntiInjected : IHttpModule
    {
        public void Init(HttpApplication application)
        {
            application.BeginRequest += (new
            EventHandler(this.Application_BeginRequest));
        }
        private void Application_BeginRequest(Object source, EventArgs e)
        {
            ProcessRequest pr = new ProcessRequest();
            pr.StartProcessRequest();
        }
        public void Dispose()
        {
        }
    }

    public class ProcessRequest
    {
        private static string SqlStr = System.Configuration.ConfigurationSettings.AppSettings["SqlInject"].ToString();

        private static string sqlErrorPage =
            System.Configuration.ConfigurationSettings.AppSettings["SQLInjectErrPage"].ToString();


        /// <summary>
        /// 构造函数
        /// </summary>
        public ProcessRequest()
        {
           
        }

        private bool IsUploadRequest(HttpRequest request)
        {
            return StringStartsWithAnotherIgnoreCase(request.ContentType, "multipart/form-data");
        }
       
        private static bool StringStartsWithAnotherIgnoreCase(string s1, string s2)
        {
            return (string.Compare(s1, 0, s2, 0, s2.Length, true, CultureInfo.InvariantCulture) == 0);
        }

        
        #region SQL注入式攻击代码分析

        ///
        /// 处理用户提交的请求
        ///
        public void StartProcessRequest()
        {
            HttpRequest Request = System.Web.HttpContext.Current.Request;
            HttpResponse Response = System.Web.HttpContext.Current.Response;
            try
            {
                string getkeys = "";
                if (IsUploadRequest(Request)) return; //如果是流传递就退出
                string urlSource = Request.Url.ToString();
                //字符串参数
                if (Request.QueryString != null)
                {
                    for (int i = 0; i < Request.QueryString.Count; i++)
                    {
                        getkeys = Request.QueryString.Keys[i];
                        if (!ProcessSqlStr(Request.QueryString[getkeys]))
                        {
                            Response.Redirect(sqlErrorPage + "?errmsg=您输入的信息包含非法字符，请返回重新输入！&sqlprocess=true&url=" +
                                              urlSource);
                            Response.End();
                        }
                    }
                }
                
            }
            catch
            {
                // 错误处理: 处理用户提交信息!
                Response.Clear();
                Response.Write("CustomErrorPage配置错误");
                Response.End();
            }
        }

        ///
        /// 分析用户请求是否正常
        ///
        /// 传入用户提交数据
        /// 返回是否含有SQL注入式攻击代码
        private bool ProcessSqlStr(string Str)
        {
            bool ReturnValue = true;
            try
            {
                if (Str != "")
                {
                    string[] anySqlStr = SqlStr.Split('|');
                    foreach (string ss in anySqlStr)
                    {
                        if (Str.ToLower().IndexOf(ss) >= 0)
                        {
                            ReturnValue = false;
                            break;
                        }
                    }
                }
            }
            catch
            {
                ReturnValue = false;
            }
            return ReturnValue;
        }

        #endregion
    }
}
